<?php defined('SYSPATH') or die('No direct script access.');

abstract class PcOpenLogin
{
    protected static $_login_type = '';
    private static $_instance = null;

    protected $_app_key = '';
    protected $_app_secret = '';
    protected $_callback_url = '';

    public static function instance($login_type = null)
    {
        if (null === self::$_instance)
        {
            self::$_login_type = $login_type;            
            $config = Kohana::config('pcopenlogin.'.$login_type);            
            $class = 'OpenLogin_PC'.$login_type;            
            
            if (!empty($config) && $config['login_switch'] && class_exists($class))
            {
                self::$_instance = new $class;               
            }
            else
            {
                return null;
            }
        }
        return self::$_instance;
    }

    public static function check_state()
    {
        if (Session::instance()->get('_openlogin_state') != $_REQUEST['state']) return false;
        return true;
    }

    public static function user_info($key = '')
    {
        static $user_info;
        if (null === $user_info)
        {
            $user_info['uid'] = Session::instance()->get('uid');
            $user_info['nickname'] = Session::instance()->get('nickname');
            $user_info['header_url'] = Session::instance()->get('header_url');
            $user_info['openid'] = Session::instance()->get('openid');
        }
        return $key ? Arr::get($user_info, $key) : $user_info;
    }

    public static function is_login()
    {
        return (bool) self::user_info('uid');
    }

    public static function login($info)
    {
        Session::instance()->set('uid', $info['uid']);
        Session::instance()->set('nickname', $info['nickname']);
        Session::instance()->set('header_url', $info['header_url']);
        Session::instance()->set('openid', $info['openid']);
        //登录奖励1抽奖机会
        Lottery_Count::add($info['uid'], 'login', 1);
    }

    public static function logout()
    {
        Session::instance()->delete('uid');
        Session::instance()->destroy();
    }

    
    
    public function __construct()
    {
        $config = Kohana::config('pcopenlogin.'.self::$_login_type);
        $this->_app_key     = Arr::get($config, 'app_key');
        $this->_app_secret  = Arr::get($config, 'app_secret');
        $this->_callback_url = Arr::get($config, 'callback_url');
    }

    protected function state()
    {
        $state = md5(uniqid(rand(10, 99), true));
        Session::instance()->set('_openlogin_state', $state);
        return $state;
    }

    abstract public function get_login_url();

    abstract public function get_access_token();

    abstract public function get_openid($access_token);

    abstract public function get_user_info($openid, $access_token);
}